//
//  LoginViewController.m
//  mosad_hw_fin
//
//  Created by student9 on 2021/1/5.
//  Copyright © 2021 student9. All rights reserved.
//

#import "LoginViewController.h"

@interface LoginViewController () {
    NSString *name;
    NSString *password;
}
@property (nonatomic, strong) UILabel *warningLabel;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"登录";
    // Do any additional setup after loading the view.
    __weak typeof(self) weakSelf = self;
    // 主图标
    self.navigationController.navigationBar.hidden = YES;
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    UIButton *back_btn;
    back_btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    back_btn.frame = CGRectMake(0, 0, 40, 40);
    back_btn.backgroundColor = [UIColor colorWithPatternImage:[[UIImage imageNamed:@"leftarrow.png"] TransformtoSize:CGSizeMake(40, 40)]];
    [back_btn addTarget:self
                  action:@selector(back_to_mine:)
        forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:back_btn];
    [back_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset(30);
        make.left.equalTo(weakSelf.view).offset(20);
        make.size.mas_equalTo(CGSizeMake(40, 40));
    }];
    
//    [self.navigationController setToolbarHidden:YES animated:YES];
    UIImage *mainicon = [[UIImage imageNamed:@"lanren_bck.png"] TransformtoSize:CGSizeMake(200, 200)];
    UIImageView *mainIconView = [[UIImageView alloc] initWithImage:mainicon];
    [self.view addSubview:mainIconView];
    [mainIconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset(weakSelf.view.frame.size.height/6);
        // 添加大小约束（make就是要添加约束的控件view）
        make.size.mas_equalTo(CGSizeMake(mainicon.size.width, mainicon.size.height));
        // 添加居中约束（居中方式与self相同）
        make.centerX.equalTo(weakSelf.view.mas_centerX);
    }];
    
    // 账号框
    // 输入框主体
    JVFloatLabeledTextField *usernameTF = [[JVFloatLabeledTextField alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 100, 50)];
    // 边框线宽度
    usernameTF.layer.borderWidth = 1;
    // 边框线颜色
    usernameTF.layer.borderColor = [UIColor grayColor].CGColor;
    // 输入文字颜色
    usernameTF.textColor = [UIColor blackColor];
    // 浮动式标签的正常字体颜色
    usernameTF.floatingLabelTextColor = [UIColor grayColor];
    // 输入框成为第一响应者时,浮动标签的文字颜色.
    usernameTF.floatingLabelActiveTextColor = [UIColor blueColor];
    // 指明当输入文字时,是否下调基准线(baseline).设置为YES(非默认值),意味着占位内容会和输入内容对齐.
    usernameTF.keepBaseline = YES;
    // 允许编辑
    [usernameTF setEnabled:YES];
    // 设置初始占位符
    [usernameTF setPlaceholder:@"请输入邮箱或手机号"
                 floatingTitle:@"邮箱或手机号"];
    usernameTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    //关闭系统自动联想
    usernameTF.autocorrectionType=UITextAutocorrectionTypeNo;
    //关闭首字母大写
    usernameTF.autocapitalizationType=UITextAutocapitalizationTypeNone;
    // 设置边框类型
    [usernameTF setKeyboardType:UIKeyboardTypeDefault];
    // 设置一个左边的空白空间，防止文字直接贴边，并设置为总是显示UITextFieldViewModeAlways
    [usernameTF setLeftView:[[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 0)]];
    [usernameTF setLeftViewMode:UITextFieldViewModeAlways];
    // 设置背景颜色，为了美观设置了透明度
    UIColor *color = [UIColor whiteColor];
    usernameTF.backgroundColor = [color colorWithAlphaComponent:0.8];
    UIBezierPath * maskPathUsername = [UIBezierPath bezierPathWithRoundedRect:usernameTF.bounds cornerRadius:10];
    CAShapeLayer * maskLayerUsername = [[CAShapeLayer alloc] init];
    maskLayerUsername.frame = usernameTF.bounds;
    maskLayerUsername.path = maskPathUsername.CGPath;
    usernameTF.layer.mask = maskLayerUsername;
    // 监听事件UIControlEventEditingChanged，当输入的内容改变之后，便调用textFieldDidChangeDate
    [usernameTF addTarget:self
                   action:@selector(textFieldDidChangeUsername:)
         forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:usernameTF];
    [usernameTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset((weakSelf.view.frame.size.height/6) * 3);
        // 添加大小约束（make就是要添加约束的控件view）
        make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width - 100, 50));
        // 添加居中约束（居中方式与self相同）
        make.centerX.equalTo(weakSelf.view.mas_centerX);
    }];
    
    // 密码框
    // 输入框主体
    JVFloatLabeledTextField *passwordTF = [[JVFloatLabeledTextField alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 100, 50)];
    // 边框线宽度
    passwordTF.layer.borderWidth = 1;
    // 边框线颜色
    passwordTF.layer.borderColor = [UIColor grayColor].CGColor;
    // 输入文字颜色
    passwordTF.textColor = [UIColor blackColor];
    // 浮动式标签的正常字体颜色
    passwordTF.floatingLabelTextColor = [UIColor grayColor];
    // 输入框成为第一响应者时,浮动标签的文字颜色.
    passwordTF.floatingLabelActiveTextColor = [UIColor blueColor];
    // 指明当输入文字时,是否下调基准线(baseline).设置为YES(非默认值),意味着占位内容会和输入内容对齐.
    passwordTF.keepBaseline = YES;
    // 密码隐藏
    passwordTF.secureTextEntry = YES;
    // 允许编辑
    [passwordTF setEnabled:YES];
    // 设置初始占位符
    [passwordTF setPlaceholder:@"请输入密码"
                 floatingTitle:@"密码"];
    passwordTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    //关闭系统自动联想
    passwordTF.autocorrectionType=UITextAutocorrectionTypeNo;
    //关闭首字母大写
    passwordTF.autocapitalizationType=UITextAutocapitalizationTypeNone;
    // 设置边框类型
    [passwordTF setKeyboardType:UIKeyboardTypeDefault];
    // 设置一个左边的空白空间，防止文字直接贴边，并设置为总是显示UITextFieldViewModeAlways
    [passwordTF setLeftView:[[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 0)]];
    [passwordTF setLeftViewMode:UITextFieldViewModeAlways];
    // 设置背景颜色，为了美观设置了透明度
    UIColor *colorPassword = [UIColor whiteColor];
    passwordTF.backgroundColor = [colorPassword colorWithAlphaComponent:0.8];
    UIBezierPath * maskPathPassword = [UIBezierPath bezierPathWithRoundedRect:passwordTF.bounds cornerRadius:10];
    CAShapeLayer * maskLayerPassword = [[CAShapeLayer alloc] init];
    maskLayerPassword.frame = passwordTF.bounds;
    maskLayerPassword.path = maskPathPassword.CGPath;
    passwordTF.layer.mask = maskLayerPassword;
    // 监听事件UIControlEventEditingChanged，当输入的内容改变之后，便调用textFieldDidChangeDate
    [passwordTF addTarget:self
                   action:@selector(textFieldDidChangePassword:)
         forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:passwordTF];
    [passwordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset((weakSelf.view.frame.size.height/6) * 3 + 60);
        // 添加大小约束（make就是要添加约束的控件view）
        make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width - 100, 50));
        // 添加居中约束（居中方式与self相同）
        make.centerX.equalTo(weakSelf.view.mas_centerX);
    }];
    
    _warningLabel = [[UILabel alloc] init];
    _warningLabel.frame = CGRectMake(0, 0, self.view.frame.size.width - 100, 20);
    _warningLabel.textColor = [UIColor redColor];
    [self.view addSubview:_warningLabel];
    [_warningLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset((weakSelf.view.frame.size.height/6) * 3 + 120);
        // 添加大小约束（make就是要添加约束的控件view）
        make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width - 100, 20));
        // 添加居中约束（居中方式与self相同）
        make.centerX.equalTo(weakSelf.view.mas_centerX);
    }];
    
    // 登录确认按钮
    UIButton *login_btn;
    login_btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    login_btn.frame = CGRectMake(0, 0, self.view.frame.size.width - 100, 50);
    login_btn.backgroundColor = [UIColor colorWithRed:123/255.0 green:104/255.0 blue:238/255.0 alpha:0.8];
//    login_btn.backgroundColor = [UIColor colorWithRed:0/255.0 green:154/255.0 blue:97/255.0 alpha:1.0];
    [login_btn setTitle:@"登录" forState:UIControlStateNormal];
    [login_btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIBezierPath * maskPath = [UIBezierPath bezierPathWithRoundedRect:login_btn.bounds cornerRadius:10];
    CAShapeLayer * maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = login_btn.bounds;
    maskLayer.path = maskPath.CGPath;
    login_btn.layer.mask = maskLayer;
    [login_btn addTarget:self
                  action:@selector(ButtonView:)
        forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:login_btn];
    [login_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset((weakSelf.view.frame.size.height/6) * 3 + 150);
        // 添加大小约束（make就是要添加约束的控件view）
        make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width - 100, 50));
        // 添加居中约束（居中方式与self相同）
        make.centerX.equalTo(weakSelf.view.mas_centerX);
    }];
    
    // 注册按钮
    UIButton *register_btn;
    register_btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    register_btn.frame = CGRectMake(0, 0, self.view.frame.size.width - 100, 50);
    register_btn.backgroundColor = [UIColor colorWithRed:123/255.0 green:104/255.0 blue:238/255.0 alpha:0.8];
//    register_btn.backgroundColor = [UIColor colorWithRed:250/255.0 green:128/255.0 blue:114/255.0 alpha:1.0];
    [register_btn setTitle:@"注册" forState:UIControlStateNormal];
    [register_btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIBezierPath * maskPath_register = [UIBezierPath bezierPathWithRoundedRect:register_btn.bounds cornerRadius:10];
    CAShapeLayer * maskLayer_register = [[CAShapeLayer alloc] init];
    maskLayer_register.frame = register_btn.bounds;
    maskLayer_register.path = maskPath_register.CGPath;
    register_btn.layer.mask = maskLayer_register;
    [register_btn addTarget:self
                     action:@selector(RegisterViewPush:)
           forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:register_btn];
    [register_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).offset((weakSelf.view.frame.size.height/6) * 3 + 210);
        // 添加大小约束（make就是要添加约束的控件view）
        make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width - 100, 50));
        // 添加居中约束（居中方式与self相同）
        make.centerX.equalTo(weakSelf.view.mas_centerX);
    }];
    
}

- (void) textFieldDidChangeUsername:(UITextField*) sender {
    self->name = sender.text;
}

- (void) textFieldDidChangePassword:(UITextField*) sender {
    self->password = sender.text;
}

- (void)ButtonView:(UIButton *)buttonView {
//    [self doPostRequestWithName:@"1220298052" WithPassword:@"xht123456"];
    NSLog(@"%@, %@", self->name, self->password);
    if (self->name == nil || self->name == NULL || [self->name isEqualToString:@""] || self->password == nil || self->password == NULL || [self->password isEqualToString:@""]) {
        self->_warningLabel.text = @"账号或密码不能为空";
    } else {
        [self doPostRequestWithName:self->name WithPassword:self->password];
    }
}

- (void) doPostRequestWithName: (NSString *)name
                  WithPassword: (NSString *)pwd {
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    NSDictionary *dict = @{
                           @"ID":name,
                           @"Password":pwd
                           };
    NSLog(@"dict: %@", dict);
    headimageModel *current_head_image = [headimageModel shareInstance];
    NSString *current_url = [current_head_image.host_str stringByAppendingString:@"User/Login"];
    [manager POST:current_url
       parameters:dict
          headers:nil
         progress:^(NSProgress * _Nonnull downloadProgress) {
             //进度
         } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             // 请求成功
             if ([responseObject[@"state"] boolValue]) {
                 dispatch_async(dispatch_get_main_queue(), ^{
                     self->_warningLabel.text = @"";
                     headimageModel *current_head_image = [headimageModel shareInstance];
                     current_head_image.headimage_url = @"login.png";
                     current_head_image.name = responseObject[@"response"];
                     current_head_image.ID = name;
                     [self.navigationController popViewControllerAnimated:NO];
                     [self.window.rootViewController childViewControllers];
                 });
             } else {
                 dispatch_async(dispatch_get_main_queue(), ^{
                     self->_warningLabel.text = @"账号或密码不正确";
                 });
             }
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
             // 请求失败
         }];
}

- (void)back_to_mine:(UIButton *)buttonView {
    NSLog(@"back_to_mine");
    [self.navigationController popViewControllerAnimated:NO];
}

- (void)RegisterViewPush: (UIButton *)buttonView {
    NSLog(@"button2!");
    RegisterViewController *registerview = [[RegisterViewController alloc] init];
    registerview.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:registerview animated:NO];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
